﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using ESF.General;

#endregion


namespace ESF.DNS.Helper
{
	public static class DNSHelper
	{
		public static IPAddress GetDnsAdress()
        {
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
 
            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if (networkInterface.OperationalStatus == OperationalStatus.Up)
                {
                    IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                    IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
 
                    foreach (IPAddress dnsAdress in dnsAddresses)
                    {
                        return dnsAdress;
                    }
                }
            }
 
            throw new InvalidOperationException("Unable to find DNS Address");
        }


		public static Answer GetMXFirstRecord (string pEmailDomain)
		{
			Answer [] result;


			result = GetMXRecords (pEmailDomain);

			if (DataHelper.IsEmpty (result))
			{
				return null;
			}
			
			return result.First ();
		}


		public static Answer [] GetMXRecords (string pEmailDomain)
		{
			Request request = new Request();


			// create a question for this domain and DNS CLASS
			request.AddQuestion(new Question(pEmailDomain, DnsType.MX, DnsClass.IN));

			// send it to the DNS server and get the response
			Response response = Resolver.Lookup(request, GetDnsAdress ());

			// check we have a response
			if (response == null)
			{
				return null;

			}
			// display each RR returned
			Console.WriteLine("--------------------------------------------------------------");

			// display whether this is an authoritative answer or not
			if (response.AuthoritativeAnswer)
			{
				Console.WriteLine("authoritative answer");
			}
			else
			{
				Console.WriteLine("Non-authoritative answer");
			}

			return response.Answers;
		}
	}
}
